package example;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 传输控制协议 TCP
 */
public class TcpClient {
    public static void main(String args[]) {
        try {
            System.out.println("客户端启动，连接服务器");
            Socket socket = new Socket("127.0.0.1", 1818);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello".getBytes());
            socket.shutdownOutput();

            InputStream inputStream = socket.getInputStream();
            StringBuffer buffer = new StringBuffer();
            byte byt[] = new byte[1];
            int len = 0;
            while ( (len = inputStream.read(byt, 0, byt.length)) != -1 ) {
                String string = new String(byt, 0, len);
                buffer.append(string);
            }
            socket.shutdownInput();
            System.out.println("服务端返回消息: " + buffer.toString());

            outputStream.close();
            inputStream.close();
            socket.close();
            System.out.println("客户端断开");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}





